<template>
  <div class="cardItem">
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div>
            {{qaname}}
          </div>
          <div class="itemContent">
            <div>
              {{'类别：'+questionnaireType}} {{ '状态：'+qastring }} {{ '答卷数量：' + qacount + '    ' }} {{'创建时间：'+qatime}}
            </div>
          </div>
        </div>
      </template>

      <div class="itemEditBtn">
        <el-button  type="primary" icon="el-icon-view" size="mini" @click="previewBtn">预览问卷</el-button>
        <el-button  icon="el-icon-edit" size="mini" @click="editBtn" :disabled="qastatus">编辑问卷</el-button>
        <el-button  v-show="!qastatus" icon="el-icon-share" size="mini" @click="publishBtn">发布问卷</el-button>
        <el-button  v-show="qastatus" icon="el-icon-share" size="mini" @click="closePublishBtn">关闭问卷</el-button>
        <el-button  icon="el-icon-paperclip" size="mini" @click="fillBtn" :disabled="!qastatus">填写链接</el-button>
        <el-button  icon="el-icon-s-data" size="mini" @click="analyzeBtn" :disabled="!isReturned">分析问卷</el-button>
      </div>

      <div class="itemManageBtn">
        <el-button  icon="el-icon-document-add" size="mini" circle @click="duplicateBtn"></el-button>
        复制
        <el-button  icon="el-icon-download" size="mini" circle @click="downloadQA"></el-button>
        下载
        <el-button  type="danger" size="mini" icon="el-icon-delete" circle @click="deleteQA(qaid)"></el-button>
        删除
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";


export default {
  name: "QAItem",
  data() {
    return {
    }
  },
  computed: {
    qastring(){
      if(this.qastatus === true) {
        return '已发布'
      }
      else {
        return '未发布'
      }
    },
    isReturned() {
      return this.qacount >= 1;
    },
    questionnaireType() {
      if (this.qtype === null) {
        return '普通问卷'
      }
      else {
        switch (this.qtype) {
          case 'sign': return '报名问卷'
          case 'exam': return '考试问卷'
          case 'card': return '打卡问卷'
          case 'vote': return '投票问卷'
        }
        // return this.qtype
      }
    }
  },
  props: ['qaname', 'qaid', 'qastatus', 'qatime', 'qacount', 'qtype'],
  mounted() {
  },
  methods: {
    varifyId() {
      let qaid = this.qaid
      let userid = localStorage.getItem('id')
      if (userid == null) {
        const { href } = this.$router.resolve({
          path: '/login',
        });
        window.open(href,'_self')

      }

      let data = {
        qaid:qaid,
        userid:userid,
      }
      let isCreated = false
      axios.post('api/qamanage/checkqa',qs.stringify(data)).then(res => {
        isCreated = res.data.data.isCreated
        // console.log(res);
      })
      if (isCreated === true) {
        return true
      }
      else if (isCreated === false) {
        return false
      }
      else {
        return null
      }
    },

    // 编辑问卷按钮
    editBtn() {
      let modifyUrl = '/edit'
      if (this.qtype != null) {
        modifyUrl = '/edit/'+this.qtype
      }

      let qaid = this.qaid
      if (this.qacount>0) { // 曾经被编辑过，继续会清空数据
        this.$confirm('此问卷曾发布过且已经获得答卷数据, 编辑将清空历史答卷数据，是否继续?', '提示', {
          confirmButtonText: '清空数据并编辑',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('清除数据');
          // 请求删除接口
          const data = {questionnaireId: this.qaid}
          axios.post('/api/qamanage/delAns', qs.stringify(data)).then(res => {
            if (res.data.code === 0) {
              const { href } = this.$router.resolve({
                path: modifyUrl,
                query: {
                  questionnaireId: qaid
                }
              });
              window.open(href,'_self')
            }
            else {
              console.log('删除接口出错');
            }
          })
        });
      }
      else {
        const { href } = this.$router.resolve({
          path: modifyUrl,
          query: {
            questionnaireId: qaid
          }
        });
        window.open(href,'_self')
      }

      // else {
      //   console.log('接口验证验证问卷与创建者错误');
      //   const { href } = this.$router.resolve({
      //     path: '/',
      //   });
      //   window.open(href,'_self')
      // }
    },

    // 发布问卷按钮
    publishBtn() {
      let qaid = this.qaid
      // TODO: varify有bug
      // let isCreated = this.varifyId()
      let isCreated = true
      if (isCreated === false) {
        const { href } = this.$router.resolve({
          path: '/login',
        });
        window.open(href,'_self')
      }
      else if (isCreated === true) {
        // 链接请求API
        let data = {
          id: qaid,
          type: this.qtype,
        }
        let url = ''
        axios.post('/api/qamanage/update/publish', qs.stringify(data)).then(res => {
          console.log(res);
          url = res.data.data.url
          console.log(url);


          // 弹窗处理
          const photo = res.data.data.img
          this.$alert('您的问卷已发布，填写链接为：\n'+url + "<div>填写二维码：<strong><img src=" + photo + " width=200px height=200px ></strong></div>", '提示', {
            confirmButtonText: '复制',
            dangerouslyUseHTMLString: true,
            callback: action => {
              console.log(url);
              const input = document.createElement('input')
              input.value = url
              document.body.appendChild(input)
              input.select()
              document.execCommand('copy')
              this.$message.success('已复制到粘贴板')
              document.body.removeChild(input)

              // 向父传递
              this.$emit('publishrefresh', qaid)
            }
          });

        })
      }
      else {
        console.log('接口验证验证问卷与创建者错误');
        const { href } = this.$router.resolve({
          path: '/',
        });
        window.open(href,'_self')

      }
    },

    // 分析问卷按钮
    analyzeBtn() {
      let qaid = this.qaid
      let isCreated = this.varifyId()
      //TODO: 删除此处
      isCreated = true
      if (isCreated === false) {
        const { href } = this.$router.resolve({
          path: '/login',
        });
        window.open(href,'_self')
      }
      else if (isCreated === true) {
        console.log(qaid);
        const { href } = this.$router.resolve({
          path: '/analysis',
          query: {
            questionnaireId: qaid
          }
        });
        window.open(href,'_self')

      }
      else {
        console.log('接口验证验证问卷与创建者错误');
        const { href } = this.$router.resolve({
          path: '/',
        });
        window.open(href,'_self')

      }
    },

    // 关闭问卷按钮
    closePublishBtn(){
      let qaid = this.qaid
      let isCreated = this.varifyId()
      //TODO: 删除此处
      isCreated = true
      if (isCreated === false) {
        const { href } = this.$router.resolve({
          path: '/login',
        });
        window.open(href,'_self')
      }
      else if (isCreated === true) {
        // 进行弹窗
        this.$confirm('此操作将停止他人填写问卷, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '关闭问卷成功!',
          });
          this.stopPublishQuestionnaire(qaid)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消关闭问卷'
          });
        });
      }
    },

    // 关闭问卷处理请求API
    stopPublishQuestionnaire(qaid){
      console.log('success');
      let data = {
        id: qaid
      }
      let status = 0

      axios.post('api/qamanage/update/stopPublish', qs.stringify(data)).then(res => {
        status = res.data.code
        if (status === 0) {
          this.$emit('stoppublishrefresh',this.qaid)
        }
      })
    },

    deleteQA(qaid) {
      let msg = '问卷删除后将进入回收问卷处，请确认是否删除'
      if (this.qastatus === true) {
        msg = '删除问卷将停止他人填写答卷，问卷删除后将进入回收问卷处，请确认是否删除'
      }

      this.$confirm(msg, '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
          .then(() => {
            this.$message({
              type: 'info',
              message: '已删除'
            });
            this.emitDeleteFunc(qaid)
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel'
                  ? '取消删除'
                  : '取消删除'
            })
          });
    },

    emitDeleteFunc(qaid) {
      this.$emit('deleteqa')
    },

    // 填写问卷按钮
    fillBtn() {
      const data = {
        qid: this.qaid
      }
      axios.post('/api/qamanage/link', qs.stringify(data)).then(res => {
        console.log(res);
        // 正常返回
        if (res.data.code === 0) {

          console.log(res.data.data.url);
          console.log(res.data.data.img);

          // 弹窗处理
          const photo = res.data.data.img
          this.$alert('您的问卷填写链接为：\n'+res.data.data.url + "<div>填写二维码：</div><div><img src=" + photo + " width=150px height=150px></div>", '提示', {
            confirmButtonText: '复制',
            dangerouslyUseHTMLString: true,
            callback: action => {
              console.log(res.data.data.url);
              const input = document.createElement('input')
              input.value = res.data.data.url
              document.body.appendChild(input)
              input.select()
              document.execCommand('copy')
              this.$message.success('已复制到粘贴板')
              document.body.removeChild(input)
            }
          });

        }
        else {
          console.log('打开链接二维码出现问题');
        }
      })
    },

    // 预览问卷按钮
    previewBtn() {
      //TODO: 预览问卷
      console.log('预览问卷按钮BTN');
      let path = null
      console.log(this.qtype);
      if(this.qtype == null) {
        path = '/fill/preSight'
      }else{
        path = '/fill/preSight/' + this.qtype
      }
      const { href } = this.$router.resolve({
        path: path,
        query: {
          questionnaireId: this.qaid,
        }
      });
      // switch(this.qtype) {
      //   case 'exam':
      //     { href } = this.$router.resolve({
      //       path: '/fill/preSight/exam',
      //       query: {
      //         questionnaireId: this.qaid,
      //       }
      //     });
      //     break
      //   case 'sign':
      //     href = this.$router.resolve({
      //       path: '/fill/preSight/sign',
      //       query: {
      //         questionnaireId: this.qaid,
      //       }
      //     });
      //     break
      //   case 'card':
      //     href = this.$router.resolve({
      //       path: '/fill/preSight/card',
      //       query: {
      //         questionnaireId: this.qaid,
      //       }
      //     });
      //     break
      //   case 'vote':
      //      href  = this.$router.resolve({
      //       path: '/fill/preSight/vote',
      //       query: {
      //         questionnaireId: this.qaid,
      //       }
      //     });
      //     break
      //   default:
      //     href  = this.$router.resolve({
      //       path: '/fill/preSight',
      //       query: {
      //         questionnaireId: this.qaid,
      //       }
      //     });
      //     break
      // }
      window.open(href,'_blank')
    },

    // 复制问卷按钮
    duplicateBtn() {
      console.log('复制问卷按钮BTN');

      this.$confirm('此操作将复制一份问卷，原问卷数据不会被复制，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //开始请求数据
        const data = {
          id: localStorage.getItem('id'),
          qid: this.qaid
        }
        //TODO: 此处复制后数据丢失
        axios.post('/api/qamanage/copy', qs.stringify(data)).then(res => {
          console.log(res);
          if (res.data.code === 0) {
            console.log('成功复制')
            this.$message({
              type: 'success',
              message: '复制问卷成功!',
            });
            // this.$router.go(0)
            this.$emit('duplicateQA')
          }
          else {
            this.$message({
              type: 'alert',
              message: '问卷复制失败，请稍后再试',
            })
          }
        })
        // this.stopPublishQuestionnaire(qaid)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消复制问卷'
        });
      });

    },

    downloadQA() {
      const data = {
        questionnaireId: this.qaid
      }

      const { href } = this.$router.resolve({
        path: '/api/qamanage/downloadPDF',
        query: {
          questionnaireId: this.qaid
        }
      })
      window.open(href, '_blank')

      //
      // axios.get('api/qamanage/downloadPDF', {params: data}).then(res => {
      //   console.log(res);
      //   if (res.data.code === 0) {
      //     console.log('成功');
      //   }
      // })

    }
  }
}
</script>

<style scoped>
  .cardItem {
    margin-right: 30px;
    margin-bottom: 15px;
  }
  .editbtn {
    background-color: white;
  }
  .itemContent {
    font-size: 12px;
    align-items: center;
    margin-top: 10px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .text {
    font-size: 14px;

  }

  .box-card {
    width: 100%;
  }

  .itemEditBtn {
    margin-bottom: 18px;
    float: left;
  }

  .floatLeft {
    float: left;
  }

  .itemManageBtn {
    margin-bottom: 18px;
    font-size: 10px;
    float: right;
  }

  * {
    -webkit-user-select: text;
  }
</style>